<template>
	<view class="coupon-center">
		<!-- 顶部搜索栏 -->
		<view class="search-bar">
			<view class="search-input">
				<uni-icons type="search" size="18" color="#999"></uni-icons>
				<input
					v-model="searchKeyword"
					placeholder="搜索优惠券"
					placeholder-style="color: #999"
					@confirm="onSearch"
					confirm-type="search"
				/>
			</view>
		</view>

		<!-- 分类筛选 -->
		<view class="category-filter">
			<scroll-view scroll-x="true" class="category-scroll">
				<view class="category-list">
					<view
						v-for="(category, index) in categories"
						:key="index"
						class="category-item"
						:class="{ active: currentCategory === category.value }"
						@click="selectCategory(category.value)"
					>
						{{ category.label }}
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 优惠券列表 -->
		<scroll-view
			class="coupon-scroll"
			scroll-y="true"
			@scrolltolower="loadMore"
			refresher-enabled="true"
			@refresherrefresh="onRefresh"
			:refresher-triggered="refreshing"
		>
			<view class="coupon-list">
				<CouponItem
					v-for="coupon in coupons"
					:key="coupon.id"
					:coupon="coupon"
					@receive="receiveCoupon"
				/>
			</view>

			<!-- 空状态 -->
			<view v-if="coupons.length === 0 && !loading" class="empty-state">
				<image src="/static/empty-coupon.svg" class="empty-image" mode="aspectFit"></image>
				<text class="empty-text">暂无相关优惠券</text>
			</view>

			<!-- 加载状态 -->
			<view v-if="loading" class="loading-state">
				<uni-icons type="spinner-cycle" size="20" color="#999"></uni-icons>
				<text>加载中...</text>
			</view>

			<!-- 加载更多 -->
			<view v-if="hasMore && coupons.length > 0 && !loading" class="load-more">
				<text>上拉加载更多</text>
			</view>

			<!-- 没有更多 -->
			<view v-if="!hasMore && coupons.length > 0" class="no-more">
				<text>没有更多了</text>
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import CouponItem from '@/components/CouponItem.vue'

// 响应式数据
const searchKeyword = ref('')
const currentCategory = ref('all')
const categories = ref([])
const coupons = ref([])
const loading = ref(false)
const refreshing = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const pageSize = 10

// 方法
const loadCoupons = async (isRefresh = false) => {
	if (loading.value) return

	loading.value = true

	try {
		const params = {
			category: currentCategory.value,
			keyword: searchKeyword.value.trim(),
			page: isRefresh ? 1 : currentPage.value,
			pageSize: pageSize
		}

		const response = await getCouponList(params)

		if (response.code === 200) {
			if (isRefresh) {
				coupons.value = response.data.list
				currentPage.value = 1
			} else {
				coupons.value.push(...response.data.list)
			}

			hasMore.value = response.data.hasMore

			if (!isRefresh) {
				currentPage.value++
			}
		}
	} catch (error) {
		console.error('加载优惠券失败:', error)
		uni.showToast({
			title: '加载失败',
			icon: 'none'
		})
	} finally {
		loading.value = false
		refreshing.value = false
	}
}

const loadCategories = async () => {
	try {
		const response = await getCouponCategories()
		if (response.code === 200) {
			categories.value = response.data
		}
	} catch (error) {
		console.error('加载分类失败:', error)
	}
}

const selectCategory = (category) => {
	if (currentCategory.value === category) return

	currentCategory.value = category
	currentPage.value = 1
	hasMore.value = true
	loadCoupons(true)
}

const onSearch = () => {
	currentPage.value = 1
	hasMore.value = true
	loadCoupons(true)
}

const onRefresh = () => {
	refreshing.value = true
	currentPage.value = 1
	hasMore.value = true
	loadCoupons(true)
}

const loadMore = () => {
	if (hasMore.value && !loading.value) {
		loadCoupons()
	}
}

const receiveCoupon = async (coupon) => {
	if (coupon.status !== 'available') return

	uni.showLoading({
		title: '领取中...'
	})

	try {
		const response = await apiReceiveCoupon(coupon.id)

		if (response.code === 200) {
			// 找到对应的优惠券并更新状态
			const targetCoupon = coupons.value.find(c => c.id === coupon.id)
			if (targetCoupon) {
				targetCoupon.status = 'received'
			}

			uni.showToast({
				title: '领取成功',
				icon: 'success'
			})
		}
	} catch (error) {
		console.error('领取失败:', error)
		uni.showToast({
			title: error.message || '领取失败',
			icon: 'none'
		})
	} finally {
		uni.hideLoading()
	}
}

// 监听搜索关键词变化，实现实时搜索
watch(searchKeyword, () => {
	// 防抖处理
	clearTimeout(window.searchTimer)
	window.searchTimer = setTimeout(() => {
		onSearch()
	}, 500)
})

onMounted(() => {
	loadCategories()
	loadCoupons(true)
})
</script>

<style lang="scss" scoped>
.coupon-center {
	background-color: #f5f5f5;
	height: 100vh;
	display: flex;
	flex-direction: column;
}

.search-bar {
	background: #fff;
	padding: 20rpx 30rpx;

	.search-input {
		display: flex;
		align-items: center;
		background: #f8f8f8;
		border-radius: 50rpx;
		padding: 20rpx 30rpx;

		input {
			flex: 1;
			margin-left: 20rpx;
			font-size: 28rpx;
		}
	}
}

.category-filter {
	background: #fff;
	padding: 20rpx 0;
	margin-bottom: 20rpx;

	.category-scroll {
		white-space: nowrap;
	}

	.category-list {
		display: flex;
		padding: 0 30rpx;
	}

	.category-item {
		flex-shrink: 0;
		padding: 16rpx 32rpx;
		margin-right: 20rpx;
		background: #f8f8f8;
		border-radius: 40rpx;
		font-size: 26rpx;
		color: #666;
		transition: all 0.3s;

		&.active {
			background: $uni-color-primary;
			color: #fff;
		}
	}
}

.coupon-scroll {
	flex: 1;
	height: 0;
}

.coupon-list {
	padding: 0 30rpx;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;

	.empty-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 30rpx;
	}

	.empty-text {
		font-size: 28rpx;
		color: #999;
	}
}

.loading-state {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 40rpx;
	color: #666;
	font-size: 28rpx;

	text {
		margin-left: 10rpx;
	}
}

.load-more {
	text-align: center;
	padding: 40rpx;
	color: #666;
	font-size: 28rpx;
}

.no-more {
	text-align: center;
	padding: 40rpx;
	color: #999;
	font-size: 24rpx;
}
</style>
